/**
 * 
 */
package com.ken.work.tools.tools.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ken.work.tools.tools.Contants;

/**
 * @desc {驼峰法-下划线互转}
 * @author Liuk
 * @date 2017年4月20日 下午6:50:19
 * @version v1.0-
 */
public class UnderlineCamel {
	
	
	public static String underline2Camel(String line,boolean smallCamel,String pre){
		//去除前缀
		if(line!=null&&!"".equals(line)) {
			if(Contants.table_pre != null && !"".equals(Contants.table_pre)) {
				if(line.toLowerCase().indexOf(pre) == 0) {
					line = line.toLowerCase().replaceFirst(pre, "");
				}
	        }
		}
        
		return underline2Camel(line, smallCamel);
	}
	
	/**
     * 下划线转驼峰法
     * @param line 源字符串
     * @param smallCamel 大小驼峰,是否为小驼峰
     * @return 转换后的字符串
     */
    public static String underline2Camel(String line,boolean smallCamel){
        if(line==null||"".equals(line)){
            return "";
        }
        
       
        
        StringBuffer sb=new StringBuffer();
        Pattern pattern=Pattern.compile("([A-Za-z\\d]+)(_)?");
        Matcher matcher=pattern.matcher(line);
        while(matcher.find()){
            String word=matcher.group();
            sb.append(smallCamel&&matcher.start()==0?Character.toLowerCase(word.charAt(0)):Character.toUpperCase(word.charAt(0)));
            int index=word.lastIndexOf('_');
            if(index>0){
                sb.append(word.substring(1, index).toLowerCase());
            }else{
                sb.append(word.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }
    
    
    /**
     * 驼峰法转下划线
     * @param line 源字符串
     * @return 转换后的字符串
     */
    public static String camel2Underline(String line){
        if(line==null||"".equals(line)){
            return "";
        }
        line=String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
        StringBuffer sb=new StringBuffer();
        Pattern pattern=Pattern.compile("[A-Z]([a-z\\d]+)?");
        Matcher matcher=pattern.matcher(line);
        while(matcher.find()){
            String word=matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end()==line.length()?"":"_");
        }
        return sb.toString();
    }
    
    
    /**
     * 首字母大写
     * @param line
     * @return
     */
    public static String getFirstUpper(String line){
    	if(line != null){
    		StringBuilder sBuilder = new StringBuilder();
    		sBuilder.append(line.substring(0, 1).toUpperCase());
    		sBuilder.append(line.substring(1, line.length()));
    		return sBuilder.toString();
    	}
    	return line;
    }
    
    
    public static void main(String[] args) {
        String line="I_HAVE_AN_IPANG3_PIG";
        String camel=underline2Camel(line,true);
        System.out.println(camel);
        System.out.println(getFirstUpper(camel));
        System.out.println(camel2Underline(camel));
    }
}
